package com.fujimana.android.manacode.converter.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fujimana.android.manacode.converter.BaseConverter;
import com.fujimana.android.manacode.converter.Options;
import com.fujimana.android.manacode.converter.Token;
import com.fujimana.android.manacode.converter.TokenAccessor;
import com.fujimana.android.manacode.converter.TokenMatcher;

public class TextConverter extends BaseConverter {
	
	private List<TokenMatcher> matchers = new ArrayList<TokenMatcher>();

	public TextConverter(Options options) {
		super(options);
		
		this.matchers = new ArrayList<TokenMatcher>();
		this.matchers.add(new TextTokenMatcher(getOptions()));
	}

	@Override
	public List<TokenMatcher> getTokenMatchers() {
		return matchers;
	}

	class TextTokenMatcher extends TokenMatcher {
		
		private StringBuilder sb;
		
		protected TextTokenMatcher(Options options) {
			super(options);
			this.sb = new StringBuilder();
		}
		
		@Override
		public boolean isMatch(String token, TokenAccessor accessor) throws IOException {
			sb.append(token);
			
			String word = null;
			while(true) {
				word = accessor.next();
				
				if(word.equals("\n")) {
					break;
				} else if(word.startsWith("\"") && word.endsWith("\"")) {
					break;
				} else if(word.startsWith("'") && word.endsWith("'") ) {
					break;
				}
				
				sb.append(word);
			}
			
			accessor.pushBack();
			return true;
		}

		@Override
		public String getMatchString() {
			return sb.toString();
		}

		@Override
		public Token getToken(String token) {
			sb = new StringBuilder();
			return new TextToken(token, getOptions());
		}
		
	}
	
	class TextToken extends Token {

		public TextToken(String value,Options options) {
			super(value, options);
		}

		@Override
		public String getFormatedValue() {
			return getValue();
		}
		
	}

}
